package com.purchase.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.purchase.service.CouponService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.purchase.entity.AppUser;
import com.purchase.entity.WxUser;
import com.purchase.mapper.AppUserMapper;
import com.purchase.mapper.WxUserMapper;
import com.purchase.service.WxAppAuthorizeService;
import com.purchase.util.AppAuthorizeUtil;
import com.purchase.util.JavaWebToken;
import com.purchase.util.RequestForm;
import com.purchase.util.ResponseForm;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class WxAppAuthorizeServiceImpl implements WxAppAuthorizeService {

	@Autowired
	AppUserMapper appUserMapper;

	@Autowired
	WxUserMapper wxUserMapper;

	@Autowired
	private CouponService couponService;
	
	@Transactional
	@SuppressWarnings({ "unused", "rawtypes", "unchecked" })
	@Override
	public ResponseForm app2authorize(RequestForm param) {
		ResponseForm result = new ResponseForm();
		String wxUserInviteCode=null;
		if (param.getData() != null) {
			Map paramMap = (Map) param.getData();
			String code = (String) paramMap.get("code");
			Integer userStatus = 0;
			/* 获取access_token等信息 */
			Map tokenMap = AppAuthorizeUtil.getAccessTokenByCode(code);
			if (tokenMap == null) {
				result.setCode("400");
				result.setMessage("请求未获取到数据,稍后重试");
				result.setStatus(false);
				return result;
			} else if (tokenMap.get("errcode") != null) {
				result.setCode(tokenMap.get("errcode") + "");
				result.setMessage(tokenMap.get("errmsg") + "");
				result.setStatus(false);
				return result;
			}
			/* 此处获取到的参数应放在redis缓存中,后期会做用户的登录状态 */
			String accessToken = (String) tokenMap.get("access_token");
			String refreshToken = (String) tokenMap.get("refresh_token");
			String openId = (String) tokenMap.get("openid");
			/* 获取用户信息 */
			Map userInfoMap = AppAuthorizeUtil.getUserInfo(accessToken, openId);
			if (userInfoMap == null) {
				result.setCode("400");
				result.setMessage("未获取到用户信息,稍后重试");
				result.setStatus(false);
				return result;
			} else if (userInfoMap.get("errcode") != null) {
				result.setCode(tokenMap.get("errcode") + "");
				result.setMessage(tokenMap.get("errmsg") + "");
				result.setStatus(false);
				return result;
			}
			AppUser appUser = userInfoHandler(userInfoMap);
			appUser.setLatestOnlinetime(new Date());
			try {
				/*从小程序获取当前用户信息,如果获取到且用户身份为会员,并且当前app用户为普通用户,则更新为会员用户*/
				WxUser wxUser = new WxUser();
				wxUser.setUnionId(appUser.getUnionId());
				wxUser = wxUserMapper.selectOne(wxUser);
				if(wxUser!=null) {
					wxUserInviteCode = wxUser.getInviteCode();
				}
				AppUser pojo = new AppUser();
				pojo.setOpenId(openId);
				pojo=appUserMapper.selectOne(pojo);
				if (pojo != null) {
					/* 更新用户信息 */
					appUser.setUserId(pojo.getUserId());
					appUser.setWxUid(pojo.getWxUid());
					appUser.setParentInviteCode(pojo.getParentInviteCode());
					/*判断用户身份 根据小程序用户是否为会员*/
					if(wxUser!=null&&wxUser.getUserStatus()>0&&pojo.getUserStatus()==0) {
						appUser.setUserStatus(wxUser.getUserStatus());
						pojo.setUserStatus(wxUser.getUserStatus());
					}
					appUserMapper.updateByPrimaryKeySelective(appUser);
					userStatus = pojo.getUserStatus();
				} else {
					/* 新增用户 */
//					appUser = new AppUser();
					appUser.setWxUid(wxUser!=null?wxUser.getWxUid():UUID.randomUUID().toString());
					appUser.setCreateTime(new Date());
					appUser.setUserStatus(wxUser!=null&&wxUser.getUserStatus()>0?wxUser.getUserStatus():0);
					appUserMapper.insertSelective(appUser);
					userStatus = appUser.getUserStatus();

					//新用户绑定新人优惠券
					couponService.bindNewUserCoupons(appUser.getWxUid(),"APP");
				}
				Integer userId = appUser.getUserId();
				String wxUid = appUser.getWxUid();
				String verifyPhone = appUser.getVerifyPhone();

				Map<String, Object> loginInfo = new HashMap<>();
				loginInfo.put("userId", userId);
				Map userSessionInfo = new HashMap<>();
				userSessionInfo.put("sessionId", JavaWebToken.createJavaWebToken(loginInfo));
				userSessionInfo.put("wxUid", wxUid);
				userSessionInfo.put("verifyPhone", verifyPhone);
				userSessionInfo.put("userInfo", appUser);
				userSessionInfo.put("userStatus", userStatus);
				userSessionInfo.put("wxUserInviteCode", wxUserInviteCode);/*小程序端该用户绑定的推广人的推广码*/
				result.setData(userSessionInfo);
				result.setCode("200");
				result.setStatus(true);
				result.setMessage("授权成功");
				result.setTotal(0);
			} catch (Exception e) {
				e.printStackTrace();
				result.fail("400", "参数错误");
				log.error("数据库访问错误");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} else {
			result.setCode("400");
			result.setMessage("参数为空");
			result.setStatus(false);
			log.error("参数为空");
		}
		return result;
	}

	private AppUser userInfoHandler(Map userInfoMap) {
		String openId = (String) userInfoMap.get("openid");
		String nickName = (String) userInfoMap.get("nickname");
		String gender = userInfoMap.get("sex") + "";
		String headImage = (String) userInfoMap.get("headimgurl");
		String province = (String) userInfoMap.get("province");
		String city = (String) userInfoMap.get("city");
		String country = (String) userInfoMap.get("country");
		String unionId = (String) userInfoMap.get("unionid");
		AppUser appUser = new AppUser();
		if (StringUtils.isNotBlank(openId))
			appUser.setOpenId(openId);
		if (StringUtils.isNotBlank(nickName))
			appUser.setNickName(nickName);
		if (StringUtils.isNotBlank(gender))
			appUser.setGender(gender);
		if (StringUtils.isNotBlank(headImage))
			appUser.setHeadImage(headImage);
		if (StringUtils.isNotBlank(province))
			appUser.setProvince(province);
		if (StringUtils.isNotBlank(city))
			appUser.setCity(city);
		if (StringUtils.isNotBlank(country))
			appUser.setCountry(country);
		if (StringUtils.isNotBlank(unionId))
			appUser.setUnionId(unionId);
		return appUser;
	}

	@SuppressWarnings({ "unused", "rawtypes" })
	@Override
	public ResponseForm getUserInfo(RequestForm param) {
		ResponseForm result = new ResponseForm();
		if(param.getData()!=null) {
			Map paramMap = (Map) param.getData();
			String wxUid = (String) paramMap.get("wxUid");
			String tradeType = (String) paramMap.get("tradeType");
			try {
				if(StringUtils.isNotBlank(tradeType)&&"APP".equals(tradeType)) {
					AppUser appUser = new AppUser();
					appUser.setWxUid(wxUid);
					appUser = appUserMapper.selectOne(appUser);
					result.succ("操作成功", appUser);
				}
				else if (StringUtils.isNotBlank(tradeType)&&"JSAPI".equals(tradeType)) {
					WxUser wxUser = new WxUser();
					wxUser.setWxUid(wxUid);
					wxUser = wxUserMapper.selectOne(wxUser);
					result.succ("操作成功", wxUser);
				}
			} catch (Exception e) {
				e.printStackTrace();
				result.fail("400", "参数错误");
				log.error("数据库访问错误");
			}
		}else{
			result.fail("400", "参数错误");
		}
		return result;
	}

}
